<template>
  <div class="box">
    <div class="hold">
      <div v-if="showLoading" class="box-center">
        <atom-loading />
      </div>
      <template v-else>
        <!-- 工具栏 -->
        <atom-sticky>
          <div class="tool">
            <div class="title">{{ title }}</div>
            <div class="toggle" v-if="listData.length">
              <span class="btn" @click="currentMode = 0" :class="{ active: currentMode === 0 }"
                >列表</span
              >
              <div class="split"></div>
              <span class="btn" @click="currentMode = 1" :class="{ active: currentMode === 1 }"
                >卡片</span
              >
            </div>
          </div>
        </atom-sticky>
        <!-- 列表 -->
        <template v-if="currentMode === 0">
          <etf-list v-if="type === 'normal'" :stockList="listData" offsetTop="13.33vw"></etf-list>
          <ServicePackStockList
            v-else
            :detailTableData="listData"
            offsetTop="13.33vw"
          ></ServicePackStockList>
        </template>
        <!-- 卡片 -->
        <template v-else>
          <tracking-card
            v-for="(card, index) in cardData"
            :key="index"
            :buttonText="type === 'servicePack' ? '全部信号' : '详情'"
            :hasSubTitle="type === 'servicePack'"
            :stockInfo="listData[index]"
            :signals="card"
            :sortTimeType="sortTimeType"
          ></tracking-card>
        </template>
        <div class="no-more">
          <span>没有更多了~</span>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import TrackingCard from '@/components/portfolio/TrackingCard.vue';
import EtfList from '@/components/portfolio/EtfList.vue';
import ServicePackStockList from '@/components/servicePack/StockList.vue';
import { ETF_STATUS } from '@/config/portfolio';
import { reqPortfolioList } from '@/apis/portfolio.api';
import { getWebHQRealTime } from '@/utils';
import tools from '@/lib/tools';

export default {
  components: {
    TrackingCard,
    EtfList,
    ServicePackStockList,
  },
  data() {
    return {
      currentMode: 0,
      showLoading: false,
      listData: [],
      cardData: [],
      sortTimeType: '',
      title: '',
      // type:normal|servicePack
      type: '',
      // 最新的接口返回
      lastData: null,
    };
  },
  async created() {
    tools.setTitle('持仓记录');
    this.title = decodeURIComponent(window.getParam('title')) || '策略池';
    this.type = window.getParam('type') || 'normal';
    this.currentMode = window.getParam('mode') ? Number(window.getParam('mode')) : 0;

    const portfolioId = window.getParam('portfolio_id');
    if (portfolioId) {
      this.getPoolData(portfolioId);
    }
    this.sortTimeType = window.getParam('sortTimeType') || 'trade_time';
    this.$addEventListener('onShow', () => {
      this.dealHQData();
    });
  },
  methods: {
    async getPoolData(portfolio_id) {
      const query = {
        portfolio_id,
        with_records: 1,
        status_list: Object.keys(ETF_STATUS),
      };
      this.showLoading = true;
      try {
        const res = await reqPortfolioList(query);
        if (res.status_code === 0 && res?.data?.length) {
          this.handleDataList(res.data);
        }
      } catch (err) {
        const errInfo = {
          name: `PortfolioPosition.vue的getPoolData方法异常。${err.name}`,
          message: `入参为${JSON.stringify(query)}。${err.message}`,
          stack: err.stack,
          category: 'js',
        };
        _t.errorReport(errInfo);
      } finally {
        this.showLoading = false;
      }
    },
    handleDataList(list) {
      const group = list.filter(item => !!item['open_date']);
      group.sort((a, b) => (a['open_date'] < b['open_date'] ? 1 : -1));
      this.lastData = group.map(item => ({
        ...item,
        stock_code: item.code,
        stock_name: item.name,
        industry: item?.indicate_info?.industry || '',
      }));
      this.dealHQData();
    },
    dealHQData() {
      if (!this.lastData) {
        return;
      }
      getWebHQRealTime(this.lastData, arr => {
        this.sortByTime(arr.map(item => item.trade_records));
        this.listData = [...arr];
      });
    },
    sortByTime(list) {
      for (const item of list) {
        item.sort((a, b) => (a[this.sortTimeType] < b[this.sortTimeType] ? 1 : -1));
      }
      this.cardData = list;
    },
  },
};
</script>

<style lang="less" scoped>
.box {
  background: var(--bg-color-1);
  padding: 8px 6px;
  .hold {
    padding: 10px;
    background: var(--bg-color-2);
    border-radius: 6px;
    min-height: 708px;
    position: relative;
    .box-center {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
  .no-more {
    font-size: 14px;
    line-height: 18px;
    margin-top: 16px;
    color: var(--text-3);
    display: flex;
    justify-content: center;
  }
}

.tool {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  line-height: 18px;
  color: var(--text-1);
  padding: 16px 0;
  .icon-btn {
    display: flex;
    align-items: center;
    svg {
      margin-right: 4px;
    }
  }
  .title {
    display: flex;
    align-items: center;
    font-size: 18px;
    line-height: 22px;
    color: var(--text-1);
  }
  .toggle {
    display: flex;
    align-items: center;
  }
  .btn {
    color: var(--text-2);
    &.active {
      color: var(--text-1);
      font-weight: 600;
    }
  }
  .split {
    width: 1px;
    height: 12px;
    background: var(--text-4);
    margin: 0 12px;
  }
}

/deep/.atom-sticky--fixed .tool {
  padding: 16px;
  background: var(--bg-color-2);
}
</style>
